<?php


namespace App\Services\Assess;

use App\Helpers\JwtUtils;
use App\Models\Account\UserAccountModel;
use App\Models\Assess\CommentGuideLinkSkuModel;
use App\Models\Assess\OrderAndCustomersOrderDetailModel;
use App\Models\Assess\OrderAndCustomersOrderExtendModel;
use App\Models\Assess\OrderAndCustomersOrderModel;
use App\Services\BaseService;
use App\Services\Common\CommonService;
use App\Services\Common\RedisService;
use Eccang\OpenApi\Contracts\Config;
use Eccang\OpenApi\Eccang;
use Eccang\OpenApi\System\Request\UnityRequest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Config\Definition\Exception\Exception;

/**
 * 订单管理
 */
class OrderAndCustomersOrderService extends BaseService
{

    //订单类型，sale：正常销售订单，resend：重发订单，line：线下订单
    const ORDER_TYPE_SALE = 'sale';
    const ORDER_TYPE_RESEND = 'resend';
    const ORDER_TYPE_LINE = 'line';

    //创建类型：api下载的订单，upload批量上传订单，hand手工创建订单
    const CREATE_TYPE_API = 'api';
    const CREATE_TYPE_UPLOAD = 'upload';
    const CREATE_TYPE_HAND = 'hand';

    public $brandList = [
        'Orfeld',
        'Makayla',
        'Fezen',
        'Zisiz',
        'Duesi'
    ];

    public $platform = [
        'amazon'=>'amazon',
        'ebay'=>'ebay',
        'shopify'=>'shopify',
        'walmart'=>'walmart'
    ];

    public $country = [
        'US'=>'美国',
        'UK'=>'英国',
        'DE'=>'德国',
        'FR'=>'法国',
        'ES'=>'西班牙',
        'IT'=>'意大利',
        'AE'=>'阿拉伯联合酋长国',
        'AT'=>'奥地利',
        'MX'=>'墨西哥',
        'BE'=>'比利时',
        'BM'=>'百慕大',
        'CA'=>'加拿大',
        'CL'=>'智利',
        'CO'=>'哥伦比亚',
        'DK'=>'丹麦',
        'EE'=>'爱沙尼亚',
        'IL'=>'以色列',
        'IS'=>'冰岛',
        'KR'=>'韩国',
        'LU'=>'卢森堡',
        'NL'=>'荷兰',
        'PE'=>'秘鲁',
        'PH'=>'菲律宾',
        'PL'=>'波兰',
        'TR'=>'土耳其',
        'VI'=>'维尔京群岛（美国）'
    ];

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new OrderAndCustomersOrderModel();
    }


    /**
     * @Notes: 获取订单搜素配置
     * @Interface orderConfig
     * @return array
     * @author: wuyu
     * @Time: 2023/5/12   16:26
     */
    public function orderConfig()
    {
        $config = [];
        $config['brand_list'] = $this->brandList;
        $config['platform_list'] = $this->platform;
        $config['country_list'] = $this->country;

        //获取店铺名
        $config['account_list'] = RedisService::getAccountList();
        //获取分类
        $config['category_list'] = RedisService::getCategoryList();

        return message("获取成功", true,$config);

    }

    public function getList()
    {
        $param = request()->all();

        // 查询条件
        $map = [];
        $map[] = ["m.mark", '=', 1];
        // 二维码Url
        $url = getter($param, "url");
        $platformSku = getter($param, "platform_sku");
        $asin = getter($param, "asin");
        $orderId = getter($param, "order_id");
        $userAccount = getter($param, "user_account");
        $platformPaidDate = getter($param, "platformPaidDate");
        $countryCode = getter($param, "country_code");
        $platform = getter($param, "platform");
        $brand = getter($param, "brand");
        $productCategoryName1 = getter($param, "product_category_name1");
        $sort = $param['sort'] ?? 'm.platform_paid_date';
        $order = $param['order'] ?? 'DESC';
        $platformSkuStr = str_replace(['；', ',', '，', "\r\n", "\r", "\n"], ';', $platformSku);
        $asinStr = str_replace(['；', ',', '，', "\r\n", "\r", "\n"], ';', $asin);
        if (!empty($platformSkuStr)) $platformSkuArr = array_unique(explode(';', $platformSkuStr));
        if (!empty($asinStr)) $asinStr = array_unique(explode(';', $asinStr));
        if (!empty($platformPaidDate)) {
            $platformPaidDateStart = $platformPaidDate[0] ?? '';
            $platformPaidDateEnd = $platformPaidDate[1] ?? '';
            if (!empty($platformPaidDateStart)) $map[] = ["m.platform_paid_date", '>=', $platformPaidDateStart.' 01:01:01'];
            if (!empty($platformPaidDateEnd)) $map[] = ["m.platform_paid_date", '<=', $platformPaidDateEnd.' 23:59:59'];
        }

        if (!empty($url)) $map[] = ["m.url", 'like', "%{$url}%"];
        if (!empty($orderId)) $map[] = ["m.order_id", '=', $orderId];
        if (!empty($platform)) $map[] = ["m.platform", '=', $platform];

        $OrderAndCustomersOrderDetailModel = new OrderAndCustomersOrderDetailModel();
        $OrderAndCustomersOrderExtendModel = new OrderAndCustomersOrderExtendModel();

        //权限过滤 根据sku过滤
        $skuList = CommonService::skuAuth();

        $mainTable = $this->model->getTable();
        $sonTable = $OrderAndCustomersOrderDetailModel->getTable();
        $offset = (PAGE - 1) * PERPAGE;
        $model = $this->model::from("$mainTable as m")
            ->select(['m.id', 'm.order_id', 'm.platform_paid_date', 'm.user_account',
                'm.buyer_name', 'm.amount_paid', 'm.discount_val', 'm.country_code',
                'm.amount_paid', 'm.discount_val', 'm.create_time','s.brand_code','s.pic',
                's.product_category_name1','s.product_category_code2','s.product_category_code3',
                's.product_category_name1','s.product_category_name2','s.product_category_name3'])
            ->join("$sonTable as s", 's.order_id', '=', 'm.id')
            ->distinct(true)
            ->where($map);

        //获取数据总数
        $model2 = $this->model::from("$mainTable as m")
            ->select('m.id')
            ->join("$sonTable as s", 's.order_id', '=', 'm.id')
            ->distinct('m.id')
            ->where($map);
        if (!empty($platformSkuArr)) {
            $model->whereIn('s.platform_sku', $platformSkuArr);
            $model2->whereIn('s.platform_sku', $platformSkuArr);
        }
        if (!empty($asinStr)) {
            $model->whereIn('s.asin', $asinStr);
            $model2->whereIn('s.asin', $asinStr);
        }
        if (!empty($brand)) {
            $model->whereIn('s.brand_code', $brand);
            $model2->whereIn('s.brand_code', $brand);
        }
        if (!empty($productCategoryName1)) {
            $model->whereIn('s.product_category_name1', $productCategoryName1);
            $model2->whereIn('s.product_category_name1', $productCategoryName1);
        }
        if (!empty($countryCode)) {
            $model->whereIn('m.country_code', $countryCode);
            $model2->whereIn('m.country_code', $countryCode);
        }
        if (!empty($userAccount)) {
            $model->whereIn('m.user_account', $userAccount);
            $model2->whereIn('m.user_account', $userAccount);
        }
        if (!empty($skuList) && empty($platformSkuArr)) {
            $model->whereIn('s.platform_sku', $skuList);
            $model2->whereIn('s.platform_sku', $skuList);
        }
        $result = $model
//            ->orderBy('m.id', 'desc')
            ->orderBy($sort, $order)
            ->offset($offset)
            ->limit(PERPAGE)
            ->get()->toArray();
        $count = $model2
            ->count();


        //获取子信息
        $mainIds = $sonList = [];
        if (!empty($result)) {
            $mainIds = array_column($result, 'id', 'id');
            $sonList = $OrderAndCustomersOrderDetailModel->whereIn('order_id', $mainIds)->get(['order_id', 'platform_sku', 'asin', 'product_title'])->toArray();
        }
        $sonGroupList = [];
        foreach ($sonList as $kk => $vv) {
            $sonGroupList[$vv['order_id']][] = $vv;
        }

        $list = [];
        if ($result) {

            $ids = array_column($result, 'id');
            $extendData = $OrderAndCustomersOrderExtendModel->whereIn('order_id', $ids)->get()->toArray();
            $extendCol = array_column($extendData, null, 'order_id');

            foreach ($result as $val) {
                $info = $this->model->getInfo($val['id']);
                if (!$info) {
                    continue;
                }
                $info['asin'] = $sonGroupList[$val['id']][0]['asin'] ?? '';
                $info['platform_sku'] = $sonGroupList[$val['id']][0]['platform_sku'] ?? '';
                $info['product_title'] = $sonGroupList[$val['id']][0]['product_title'] ?? '';
                $info['line'] = '';
                if (!empty($extendCol[$val['id']]['line1'])) {
                    $info['line'] = $extendCol[$val['id']]['line1'] . ' ' . $extendCol[$val['id']]['line2'] . ' ' . $extendCol[$val['id']]['line3'];
                }
                $info['brand_code'] = $val['brand_code'];
                $info['city_name'] = $extendCol[$val['id']]['city_name'] ?? '';
                $info['postal_code'] = $extendCol[$val['id']]['postal_code'] ?? '';
                $info['district'] = $extendCol[$val['id']]['district'] ?? '';
                $info['state'] = $extendCol[$val['id']]['state'] ?? '';
                $info['pic'] = $val['pic'];
                if (!empty($val['product_category_name1'])) $info['product_category_name'] = $val['product_category_name1'] . ' / '.$val['product_category_name2'] . ' / ' . $val['product_category_name3'];
                $list[] = $info;
            }
        }
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );
        return $message;
    }

    public function status()
    {

        $params = request()->all();

        $id = $params['id'] ?? 0;
        $status = $params['status'] ?? 0;
        if (empty($id) || empty($status)) {
            return message("参数不存在", false, []);
        }
        $data = ['status' => $status];
        $this->model->where('id', $id)->update($data);
        $this->model->cacheReset($id, $data, $id);
        return message("操作成功", true, []);
    }

    /**
     * 添加或编辑
     * @return array
     * @since 2020/11/11
     * @author 牧羊人
     */
    public function edit()
    {
        DB::connection($this->model->connection)->beginTransaction(); //开启事务
        try {
            $params = request()->all();
            $data = [
                'url' => $params['url'] ?? '',
                'url_path' => $params['url_path'] ?? '',
                'url_ssl' => $params['url_ssl'] ?? '',
                'url_ssl_path' => $params['url_ssl_path'] ?? '',
                'amazon_comment_url' => $params['amazon_comment_url'] ?? '',
                'amazon_comment_url_path' => $params['amazon_comment_url_path'] ?? '',
                'sort' => $params['sort'] ?? 10,
            ];

            // 图片处理
            $urlPath = getter($data, "url_path");
            $amazonCommentUrlPath = getter($data, "amazon_comment_url_path");
            if (!empty($urlPath)) {
                $data['url_path'] = str_replace(IMG_URL, "", $urlPath);
            }
            if (!empty($amazonCommentUrlPath)) {
                $data['amazon_comment_url_path'] = str_replace(IMG_URL, "", $amazonCommentUrlPath);
            }
            $userId = JwtUtils::getUserId();
            $asin = $params['asin'] ?? '';
            if (!empty($data['create_user_name'])) unset($data['create_user_name']);
            if (!empty($data['update_user_name'])) unset($data['update_user_name']);
            if (!empty($asin)) unset($data['asin']);
            if (!empty($params['id'])) {
                $id = $params['id'];
                $data['id'] = $id;
                $data['update_time'] = time();
//                $this->model->edit($data);
                $this->model->where('id', $id)->update($data);
                $this->model->cacheReset($id, $data, $id);
            } else {
                $data['create_user'] = $data['update_user'] = $userId;
                $data['create_time'] = time();
                $id = $this->model->insertGetId($data);
            }
            if (!$id) {
                throw new \Exception('保存失败');
            }
            $CommentGuideLinkSkuModel = new CommentGuideLinkSkuModel();
            $asinStr = str_replace(['；', ',', '，', "\r\n", "\r", "\n"], ';', $asin);
            $asinArr = array_unique(explode(';', $asinStr));

            $CommentGuideLinkSkuModel->where('comments_guide_link_id', $id)->delete();

            foreach ($asinArr as $val) {
                $asinData = [
                    'comments_guide_link_id' => $id,
                    'asin' => $val,
                    'create_user' => $userId,
                    'create_time' => time()
                ];
                $CommentGuideLinkSkuModel->insert($asinData);
            }
            DB::connection($this->model->connection)->commit(); //事务提交
            return message("保存成功", true, []);

        } catch (\Exception $e) {
            DB::connection($this->model->connection)->rollBack(); //事务回滚
            return message("保存失败:" . $e->getMessage(), false, []);
        }

    }


    public function importOrder()
    {
        try {
            $params = request()->all();
            $orderCodeList = $params['order_code'] ?? '';
            if (empty($orderCodeList)){
                throw new \Exception('请输入订单号');
            }
            $orderCodeList = str_replace(['；', ',', '，', "\r\n", "\r", "\n"], ';', $orderCodeList);
            $dataList = [
                'platform_code'=>$params['platform_code'],
                'order_code_list'=>explode(';',$orderCodeList)
            ];
            $response = $this->synOrder($dataList);
            $msg = [];

            //查询订单是否同步
            $OrderAndCustomersOrderModel = new OrderAndCustomersOrderModel();
            $orderExists = $OrderAndCustomersOrderModel->whereIn('order_id',$dataList['order_code_list'])->get(['order_id'])->toArray();

            foreach ($orderExists as $val){
                $msg[] = '订单id: '.$val['order_id'].' 同步成功';
            }
            if (!empty($orderExists)){
                $order_bb = array_diff($dataList['order_code_list'],array_column($orderExists,'order_id'));
            }else{
                $order_bb = $dataList['order_code_list'];
            }

            foreach ($order_bb as $vv){
                $msg[] = '订单id: '.($vv['order_id'] ?? $vv).' 同步失败';
            }
            if (count($msg)>=1) throw new \Exception(implode('</br>',$msg));

            if (empty($response)){
                return message("同步成功", true, []);
            }
        } catch (\Exception $e) {
            return message("同步结果:".$e->getMessage(), false );
        }

    }


    /**
     * @Notes:同步订单操作
     * @Interface synOrder
     * @param $params
     * @author: wuyu
     * @Time: 2023/4/20   10:46
     */
    public function synOrder($params)
    {
        $path = dirname(__FILE__, 4);
        include $path . '/vendor/Eccang/open-api/src/include.php';
        $config = new Config();
        $request = new UnityRequest();
        $config->setBaseUri($config->eccangWeb);
        $orderCode = $params['order_code'] ?? "";
        $orderCodeList = $params['order_code_list'] ?? [];
        $status = $params['status'] ?? "4";
        $warehouseShipDate = $params['warehouse_ship_date'] ?? [];
        $condition = ['status' => $status];

        if (!empty($params['platform_code'])) $condition['platform'] = $params['platform_code'];
//        $condition['user_account_list'] = ['LBT_US'];

        if (!empty($orderCode)) $condition['order_code_list'] = [$orderCode];
        if (!empty($orderCodeList)) $condition['order_code_list'] = $orderCodeList;

        if (!empty($warehouseShipDate)) {
            $condition['platform_create_date_start'] = $warehouseShipDate['warehouse_ship_date_start'];
            $condition['platform_create_date_end'] = $warehouseShipDate['warehouse_ship_date_end'];
        }
        $orderType = $this->getOrderTypeMapping(true);
        $createType = $this->getCreateTypeMapping(true);
        $page = 0;
        $pageSize = 50;
        $OrderModel = new OrderAndCustomersOrderModel();
        $OrderExtendModel = new OrderAndCustomersOrderExtendModel();
        $OrderDetailModel = new OrderAndCustomersOrderDetailModel();
        $error = '';
        while (true) {
            $page = $page + 1;
            try {
                $requestData = [
                    'page' => $page,
                    'page_size' => $pageSize,
                    'get_detail' => 1,
                    'get_address' => 1,
                    'get_custom_order_type' => 1,
                    'condition' => $condition
                ];
                $request->getOrderList($requestData);
                sleep(1);
                $response = Eccang::system($config)->Unity($request)->getBody();
                $code = $response['code'] ?? '';
                if ($code != '200') {
                    throw new \Exception(($response['message'] ?? '接口错误'));
                }

                $bizContent = $response['biz_content']['data'] ?? [];
                if (empty($bizContent)) {
                    Log::channel('orderLog')->debug($requestData);
                    break;
                }
                foreach ($bizContent as $val) {
                    //插入数据表中
//                    $orderCode = explode('-',$val['order_code']);
                    $order_code = $val['order_code'];
//                    Log::channel('orderLog')->debug('==========易仓返回订单=============');
//                    Log::channel('orderLog')->debug($order_code);
//                    if (count($orderCode)>3) $order_code=$val['refrence_no_sys'];
                    $orderData = [
                        'order_id' => $order_code,
                        'platform' => $val['platform'] ?? '',
                        'order_type' => $orderType[$val['order_type']] ?? 0,
                        'create_type' => $createType[$val['create_type']] ?? 0,
                        'platform_status' => $val['status'] ?? 0,
                        'refrence_no' => $val['refrence_no'] ?? '',
                        'order_code' => $val['order_code'] ?? '',
                        'refrence_no_sys' => $val['refrence_no_sys'] ?? '',
                        'warehouse_order_code' => $val['warehouse_order_code'] ?? '',
                        'company_code' => $val['company_code'] ?? '',
                        'user_account' => $val['user_account'] ?? '',
                        'platform_user_name' => $val['platform_user_name'] ?? '',
                        'shipping_method' => $val['shipping_method'] ?? '',
                        'shipping_method_no' => $val['shipping_method_no'] ?? '',
                        'shipping_method_platform' => $val['shipping_method_platform'] ?? '',
                        'warehouse_id' => $val['warehouse_id'] ?? '',
                        'warehouse_code' => $val['warehouse_code'] ?? '',
                        'date_create' => $this->getDateTime(($val['date_create'] ?? '')),
                        'platform_update_date' => $this->getDateTime(($val['update_date'] ?? '')),
                        'platform_paid_date' => $this->getDateTime(($val['platform_paid_date'] ?? '')),
                        'date_create_platform' => $this->getDateTime(($val['date_create_platform'] ?? '')),
                        'platform_ship_status' => intval($val['platform_ship_status']),
                        'platform_ship_date' => $this->getDateTime(($val['platform_ship_date'] ?? '')),
                        'warehouse_ship_date' => $this->getDateTime(($val['warehouse_ship_date'] ?? '')),
                        'platform_latest_ship_date' => $this->getDateTime(($val['platform_latest_ship_date'] ?? '')),
                        'currency' => $val['currency'],
                        'amount_paid' => number_format((float)($val['amountpaid'] ?? 0.00), 2, ".", ""),
                        'sub_total' => number_format((float)($val['subtotal'] ?? 0.00), 2, ".", ""),
                        'ship_fee' => number_format((float)($val['ship_fee'] ?? 0.00), 2, ".", ""),
                        'platform_fee_total' => number_format((float)($val['platform_fee_total'] ?? 0.00), 2, ".", ""),
                        'finalvalue_fee_total' => number_format((float)($val['finalvalue_fee_total'] ?? 0.00), 2, ".", ""),
                        'other_fee' => number_format((float)($val['other_fee'] ?? 0.00), 2, ".", ""),
                        'cost_ship_fee' => number_format((float)($val['cost_ship_fee'] ?? 0.00), 2, ".", ""),
                        'buyer_id' => $val['buyer_id'] ?? '',
                        'buyer_name' => $val['buyer_name'] ?? '',
                        'buyer_mail' => $val['buyer_mail'] ?? '',
                        'site' => $val['site'] ?? '',
                        'recipient_country_code' => $val['country_code'] ?? '',
                        'product_count' => intval($val['product_count'] ?? 0),
                        'order_weight' => number_format((float)($val['order_weight'] ?? 0.00), 2, ".", ""),
                        'paypal_transaction_id' => $val['paypal_transaction_id'] ?? '',
                        'payment_method' => $val['payment_method'] ?? '',
                        'abnormal_type' => intval($val['abnormal_type'] ?? 0),
                        'is_mark' => intval($val['is_mark'] ?? 0),
                        'discount_val' => number_format((float)($val['discount_val'] ?? 0.00), 2, ".", ""),
                        'date_create_sys' => $this->getDateTime(($val['date_create_sys'] ?? '')),
                        'is_business_order' => intval($val['is_business_order'] ?? 0),
                        'fba_fee' => $val['fba_fee'] ?? '',
                        'seller_rebate' => $val['seller_rebate'] ?? '',
                        'fba_shipping_date' => $this->getDateTime(($val['fba_shipping_date'] ?? '')),
                        'is_cod' => $val['is_cod'] ?? 0,
                        'is_transfer_fba_delivery' => $val['is_transfer_fba_delivery'] ?? 0,
                        'fulfillment_type' => $val['fulfillment_type'] ?? 0,
                        'tax' => number_format((float)($val['tax'] ?? 0.00), 2, ".", ""),
                        'country_code' => $val['order_address']['country_code'] ?? '',
                        'country_name' => $val['order_address']['country_name'] ?? '',

                    ];

                    //判断是否存在
                    $orderExists = $OrderModel->where([
                        ['order_id', '=', $orderData['order_id']],
                        ['platform', '=', $orderData['platform']],
                        ['user_account', '=', $orderData['user_account']]
                    ])->first('id');
                    if (empty($orderExists)) {
                        $orderData['create_user'] = 1;
                        $orderData['create_time'] = time();
                        $orderData['update_time'] = time();
                        $id = $OrderModel->insertGetId($orderData);
                    } else {
                        $orderData['update_time'] = time();
                        $OrderModel->where('id', $orderExists['id'])->update($orderData);
                        $id = $orderExists['id'];
                    }

                    //插入扩展信息表
                    $extendData = [
                        'order_id' => $id,
                        'order_desc' => $val['order_desc'] ?? '',
                        'abnormal_reason' => $val['abnormal_reason'] ?? '',
                        'customer_service_note' => $val['customer_service_note'] ?? '',
                        'paypal_account' => $val['paypal_account'] ?? '',
                        'buyer_tax_registration_id' => $val['buyer_tax_registration_id'] ?? '',
                        'recipient_name' => $val['order_address']['name'] ?? '',
                        'company_name' => $val['order_address']['company_name'] ?? '',
                        'city_name' => $val['order_address']['city_name'] ?? '',
                        'postal_code' => $val['order_address']['postal_code'] ?? '',
                        'line1' => $val['order_address']['line1'] ?? '',
                        'line2' => $val['order_address']['line2'] ?? '',
                        'line3' => $val['order_address']['line3'] ?? '',
                        'district' => $val['order_address']['district'] ?? '',
                        'state' => $val['order_address']['state'] ?? '',
                        'doorplate' => $val['order_address']['doorplate'] ?? '',
                        'phone' => $val['order_address']['phone'] ?? '',
                        'address_created_date' => $this->getDateTime(($val['order_address']['address_created_date'] ?? '')),
                        'address_update_date' => $this->getDateTime(($val['order_address']['address_update_date'] ?? ''))
                    ];
                    $ExtendExists = $OrderExtendModel->where('order_id', $id)->first('id');
                    if (empty($ExtendExists)) {
                        $OrderExtendModel->insert($extendData);
                    } else {
                        $OrderExtendModel->where('id', $ExtendExists['id'])->update($extendData);
                    }

                    //插入sku信息
                    if (!empty($val['order_details'])) {
                        foreach ($val['order_details'] as $detailVal) {
                            $detailData = [
                                'order_id' => $id,
                                'platform_sku' => $detailVal['platform_sku'] ?? '',
                                'product_sku_info' => $detailVal['product_sku_info'] ?? '',
                                'product_sku_list' => $detailVal['product_sku_list'] ?? '',
                                'product_sku_qty_list' => $detailVal['product_sku_qty_list'] ?? '',
                                'unit_price' => number_format((float)($detailVal['unit_price'] ?? 0.00), 2, ".", ""),
                                'item_price' => number_format((float)($detailVal['item_price'] ?? 0.00), 2, ".", ""),
                                'original_unit_price' => number_format((float)($detailVal['original_unit_price'] ?? 0.00), 2, ".", ""),
                                'qty' => intval($detailVal['qty'] ?? 0),
                                'product_title' => $detailVal['product_title'] ?? '',
                                'pic' => $detailVal['pic'] ?? '',
                                'op_site' => $detailVal['op_site'] ?? '',
                                'product_url' => $detailVal['product_url'] ?? '',
                                'op_ref_item_id' => $detailVal['op_ref_item_id'] ?? '',
                                'asin' => $detailVal['op_ref_item_location'] ?? '',
                                'unit_finalvaluefee' => number_format((float)($detailVal['unit_finalvaluefee'] ?? 0.00), 2, ".", ""),
                                'unit_platformfee' => number_format((float)($detailVal['unit_platformfee'] ?? 0.00), 2, ".", ""),
                                'platform_update_time' => $this->getDateTime($detailVal['update_time'] ?? ''),
                                'action' => intval($detailVal['action'] ?? 0),
                                'order_code_org' => $detailVal['order_code_org'] ?? '',
                                'op_ref_tnx' => $detailVal['op_ref_tnx'] ?? '',
                                'product_sku_org' => $detailVal['product_sku_org'] ?? '',
                                'product_sku_org_qty' => intval($detailVal['product_sku_org_qty'] ?? 0)
                            ];
                            $brand = 'NoBrand';
                            if (!empty($detailVal['product_title'])) {
                                foreach ($this->brandList as $brandV) {
                                    if (strpos(strtolower($detailVal['product_title']), strtolower($brandV)) !== false) {
                                        $brand = $brandV;
                                        break;
                                    }
                                }
                            }
                            $detailData['brand_code'] = $brand;

                            //查询sku对应的分类
                            $categoryOne = $OrderDetailModel->getOne([
                                ['platform_sku', '=', $detailData['platform_sku']],
                                ['product_category_name1','!=','']
                            ],'product_category_code1,product_category_code2,product_category_code3,product_category_name1,product_category_name2,product_category_name3',
                            false,false);

                            $detailData['product_category_code1'] = $categoryOne['product_category_code1'] ?? '';
                            $detailData['product_category_code2'] = $categoryOne['product_category_code2'] ?? '';
                            $detailData['product_category_code3'] = $categoryOne['product_category_code3'] ?? '';
                            $detailData['product_category_name1'] = $categoryOne['product_category_name1'] ?? '';
                            $detailData['product_category_name2'] = $categoryOne['product_category_name2'] ?? '';
                            $detailData['product_category_name3'] = $categoryOne['product_category_name3'] ?? '';

                            $detailExists = $OrderDetailModel->where([
                                    ['order_id', '=', $detailData['order_id']],
                                    ['platform_sku', '=', $detailData['platform_sku']]
                                ]
                            )->first();
                            if (empty($detailExists)) {
                                $OrderDetailModel->insert($detailData);
                            } else {
                                $OrderDetailModel->where('id', $detailExists['id'])->update($detailData);
                            }
                        }
                    }
                    $OrderModel->cacheReset($id, [], $id); //清除缓存
                }

            } catch (\Exception $e) {
                $log = $e->getMessage() . ' ' . $e->getFile() . ' ' . $e->getLine();
                $error.=$e->getMessage();
                Log::channel('orderLog')->debug($requestData);
                Log::channel('orderLog')->debug($log);
                if (strpos($e->getMessage(), 'Undefined array key "biz_content"') !== false || strpos($e->getMessage(), 'Undefined index: biz_content') !== false) {
                    sleep(2);
                    $page = $page - 1;
                } else {
                    break;
                }
            }
        }
        return $error;

    }


    public function synBrand($params)
    {
        $path = dirname(__FILE__, 4);
        include $path . '/vendor/Eccang/open-api/src/include.php';
        $config = new Config();
        $request = new UnityRequest();
        $config->setBaseUri($config->eccangWeb);

        //获取订单对应的sku
        $OrderAndCustomersOrderModel = new OrderAndCustomersOrderModel();
        $OrderAndCustomersOrderDetailModel = new OrderAndCustomersOrderDetailModel();
        $mainTable = $OrderAndCustomersOrderModel->getTable();
        $sonTable = $OrderAndCustomersOrderDetailModel->getTable();

        $offset = 0;
        $limit = 300;
        while (true) {
            $orderList = $OrderAndCustomersOrderModel::from("$mainTable as m")
                ->select(['m.order_id', 's.id', 's.platform_sku', 's.brand_code', 's.product_sku_list'])
                ->join("$sonTable as s", 's.order_id', '=', 'm.id')
                ->where('m.platform', '=', 'amazon')
                ->where('s.brand_code', '=', '')->offset($offset)->limit($limit)->get()->toArray();
            $offset += $limit;
            if (empty($orderList)) break;
            try {
                $dataChunk = array_chunk($orderList, 100);
                foreach ($dataChunk as $key => $info) {
                    $productSku = [];
                    foreach ($info as $vv) {
                        $productSku[] = $vv['product_sku_list'];
                    }
                    $requestData = [
                        'product_sku' => $productSku,
                    ];
                    sleep(1);
                    $request->getWmsProductList($requestData);
                    $response = Eccang::system($config)->Unity($request)->getBody();

                    $code = $response['code'] ?? '';
                    if ($code != '200') {
                        throw new \Exception(($response['message'] ?? '接口错误'));
                    }

                    $bizContent = $response['biz_content']['data'] ?? [];
                     if (empty($bizContent)) {
                        Log::channel('brandLog')->debug($requestData);
                        break;
                    }

                    foreach ($bizContent as $bizVal) {
                        if (empty($bizVal['product_title'])) {
                            $brand = 'NoBrand';
                        } else {
                            foreach ($this->brandList as $brandV) {
                                if (strpos($bizVal['product_title'], $brandV) !== false) {
                                    $brand = $brandV;
                                }
                            }
                        }
                        $images = explode(',',($bizVal['product_images'] ?? ''));
                        $pushData = [
                            'brand_code' => $brand,
                            'pic' => $images[0] ?? ''
                        ];
                        $OrderAndCustomersOrderDetailModel->where('product_sku_list', '=', $bizVal['product_sku'])->update($pushData);
                    }
                }

            } catch (\Exception $e) {
                Log::channel('brandLog')->debug($e->getMessage() . ' ' . $e->getFile() . ' ' . $e->getLine());
            }
        }

    }

    /**
     * @Notes:同步分类信息
     * @Interface synCategory
     * @param $params
     * @author: wuyu
     * @Time: 2023/6/6  9:40
     */
    public function synCategory($params)
    {
        $path = dirname(__FILE__, 4);
        include $path . '/vendor/Eccang/open-api/src/include.php';
        $config = new Config();
        $request = new UnityRequest();
        $config->setBaseUri($config->eccangWeb);

        //获取订单对应的sku
        $OrderAndCustomersOrderModel = new OrderAndCustomersOrderModel();
        $OrderAndCustomersOrderDetailModel = new OrderAndCustomersOrderDetailModel();
        $mainTable = $OrderAndCustomersOrderModel->getTable();
        $sonTable = $OrderAndCustomersOrderDetailModel->getTable();

        $sku = $params['product_sku'] ?? '';

        $offset = 0;
        $limit = 2000;
        $endTime = time()-3*24*60*60;
        while (true) {
            $model = $OrderAndCustomersOrderModel::from("$mainTable as m")
                ->select(['m.id','m.order_id', 's.id as s_id', 's.platform_sku', 's.brand_code', 's.product_sku_list'])
                ->join("$sonTable as s", 's.order_id', '=', 'm.id')
                ->where('m.platform', '=', 'amazon')
                ->where('m.update_time', '>=',$endTime)
                ->where('s.product_category_name1', '=', '');
            if (!empty($sku)) $model->where('s.platform_sku','=',$sku);
            $orderList = $model->offset($offset)->limit($limit)->get()->toArray();

             $offset += $limit;

            if (empty($orderList)) break;
//            try {
                foreach ($orderList as $key => $info) {

                    try {
                        $requestData = [
                            'product_sku' => [$info['product_sku_list']],
                        ];

                        try {
                            $request->getProductBySku($requestData);
                            $response = Eccang::system($config)->Unity($request)->getBody();
                        }catch (Exception $e){
                            Log::channel('categoryLog')->debug('发起请求异常:'.$e->getMessage().' '.$e->getFile().' '.$e->getLine());
                            continue;
                        }
                        sleep(1);

                        $code = $response['code'] ?? '';
                        if ($code != '200') {
                            Log::channel('categoryLog')->debug(($response['message'] ?? '接口错误:'.var_export($response,true)));
                            continue;
//                        throw new \Exception(($response['message'] ?? '接口错误'));
                        }

                        $bizContent = $response['biz_content']['data'] ?? [];
                        if (empty($bizContent)) {
                            Log::channel('categoryLog')->debug($requestData);
                            continue;
                        }

                        foreach ($bizContent as $bizVal) {
                            if (empty($bizVal['procut_category_code1'])) {
                                continue;
                            }

                            $pushData = [
                                'product_category_code1' => $bizVal['procut_category_code1'] ?? '',
                                'product_category_code2' => $bizVal['procut_category_code2'] ?? '',
                                'product_category_code3' => $bizVal['procut_category_code3'] ?? '',
                                'product_category_name1' => $bizVal['procut_category_name1'] ?? '',
                                'product_category_name2' => $bizVal['procut_category_name2'] ?? '',
                                'product_category_name3' => $bizVal['procut_category_name3'] ?? ''
                            ];
                            $OrderAndCustomersOrderDetailModel->where('product_sku_list','=',$info['product_sku_list'])->update($pushData);
                        }
                        sleep(2); //易仓存在判断重复发送请求问题

                    }catch (Exception $e){
                        Log::channel('categoryLog')->debug($e->getMessage() . ' ' . $e->getFile() . ' ' . $e->getLine());
                    }
                }

//            } catch (\Exception $e) {
//                Log::channel('categoryLog')->debug($e->getMessage() . ' ' . $e->getFile() . ' ' . $e->getLine());
//            }
        }

    }

    /**
     * @Notes:根据platform_sku同步分类信息
     * @Interface synCategory
     * @param $params
     * @author: wuyu
     * @Time: 2023/6/6  9:40
     */
    public function synCategoryPlatformSku($params)
    {
        $path = dirname(__FILE__, 4);
        include $path . '/vendor/Eccang/open-api/src/include.php';
        $config = new Config();
        $request = new UnityRequest();
        $config->setBaseUri($config->eccangWeb);

        //获取订单对应的sku
        $OrderAndCustomersOrderModel = new OrderAndCustomersOrderModel();
        $OrderAndCustomersOrderDetailModel = new OrderAndCustomersOrderDetailModel();
        $mainTable = $OrderAndCustomersOrderModel->getTable();
        $sonTable = $OrderAndCustomersOrderDetailModel->getTable();

        $sku = $params['product_sku'] ?? '';

        $offset = 0;
        $limit = 2000;
        $endTime = time()-3*24*60*60;
        while (true) {
            $model = $OrderAndCustomersOrderModel::from("$mainTable as m")
                ->select(['m.id','m.order_id', 's.id as s_id', 's.platform_sku', 's.brand_code', 's.product_sku_list'])
                ->join("$sonTable as s", 's.order_id', '=', 'm.id')
                ->where('m.update_time', '>=',$endTime)
                ->where('m.platform', '=', 'amazon')
                ->where('s.product_category_name1', '=', '');
            if (!empty($sku)) $model->where('s.platform_sku','=',$sku);
            $orderList = $model->offset($offset)->limit($limit)->get()->toArray();

            $offset += $limit;

            if (empty($orderList)) break;
            try {
                foreach ($orderList as $key => $info) {

                    $productSku = [];
//                    foreach ($info as $vv) {
//                        $productSku[] = $vv['product_sku_list'];
//                    }
                    $requestData = [
                        'product_sku' => [$info['platform_sku']],
                    ];

                    try {
                        $request->getProductBySku($requestData);
                        $response = Eccang::system($config)->Unity($request)->getBody();
                    }catch (Exception $e){
                        Log::channel('categoryLog')->debug('发起请求异常:'.$e->getMessage().' '.$e->getFile().' '.$e->getLine());
                        continue;
                    }

                    sleep(1);

                    $code = $response['code'] ?? '';
                    if ($code != '200') {
                        Log::channel('categoryLog')->debug(($response['message'] ?? '接口错误:'.var_export($response,true)));
                        continue;
//                        throw new \Exception(($response['message'] ?? '接口错误'));
                    }

                    $bizContent = $response['biz_content']['data'] ?? [];
                    if (empty($bizContent)) {
                        Log::channel('categoryLog')->debug($requestData);
                        continue;
                    }

                    foreach ($bizContent as $bizVal) {
                        if (empty($bizVal['procut_category_code1'])) {
                            continue;
                        }

                        $pushData = [
                            'product_category_code1' => $bizVal['procut_category_code1'] ?? '',
                            'product_category_code2' => $bizVal['procut_category_code2'] ?? '',
                            'product_category_code3' => $bizVal['procut_category_code3'] ?? '',
                            'product_category_name1' => $bizVal['procut_category_name1'] ?? '',
                            'product_category_name2' => $bizVal['procut_category_name2'] ?? '',
                            'product_category_name3' => $bizVal['procut_category_name3'] ?? ''
                        ];
                        $OrderAndCustomersOrderDetailModel->where('platform_sku','=',$info['platform_sku'])->update($pushData);
                    }
                    sleep(2); //易仓存在判断重复发送请求问题
                }

            } catch (\Exception $e) {
                Log::channel('categoryLog')->debug($e->getMessage() . ' ' . $e->getFile() . ' ' . $e->getLine());
            }
        }

    }


    /**
     * @Notes:将日期格式转换数据表格式
     * @Interface getDateTime
     * @param $dateTime
     * @author: wuyu
     * @Time: 2023/4/20   14:33
     */
    public function getDateTime($dateTime)
    {

        if (empty($dateTime)) {
            $dateTime = '1970-01-01 00:00:00';
        } elseif ($dateTime == '0000-00-00 00:00:00') {
            $dateTime = '1970-01-01 00:00:00';
        }
        return date('Y-m-d H:i:s', strtotime($dateTime));

    }


    /**
     * @Notes:获取订单类型
     * @Interface getOrderTypeMapping
     * @author: wuyu
     * @Time: 2023/4/20   12:02
     */
    public function getOrderTypeMapping($flip = false): array
    {

        $orderType = [
            1 => self::ORDER_TYPE_SALE,
            2 => self::ORDER_TYPE_RESEND,
            3 => self::ORDER_TYPE_LINE
        ];
        if ($flip) $orderType = array_flip($orderType);

        return $orderType;

    }

    /**
     * @Notes:获取创建类型
     * @Interface getCreateTypeMapping
     * @param bool $flip
     * @return int[]|string[]
     * @author: wuyu
     * @Time: 2023/4/20   12:08
     */
    public function getCreateTypeMapping(bool $flip = false): array
    {

        $createType = [
            1 => self::CREATE_TYPE_API,
            2 => self::CREATE_TYPE_UPLOAD,
            3 => self::CREATE_TYPE_HAND
        ];
        if ($flip) $createType = array_flip($createType);

        return $createType;

    }


}
